/**
 * 
 */
package com.alphasystem.commerce.common.model.translation.listener;

import static com.alphasystem.commerce.common.ErrorCodeConstant.RLNTS_NOT_DEFINED;

import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;

import com.alphasystem.commerce.common.ApplicationException;
import com.alphasystem.commerce.common.BusinessErrorCode;
import com.alphasystem.commerce.common.BusinessException;
import com.alphasystem.commerce.common.model.locale.Country;
import com.alphasystem.commerce.common.model.locale.Language;
import com.alphasystem.commerce.common.model.translation.TranslationInfo;

/**
 * @author Syed Farhan Ali
 * 
 */
public class TranslationInfoListener {

	@PrePersist
	public void prePersist(TranslationInfo translationInfo)
			throws ApplicationException {
		setTranslationKey(translationInfo);
	}

	@PreUpdate
	public void preUpdate(TranslationInfo translationInfo)
			throws ApplicationException {
		setTranslationKey(translationInfo);
	}

	private void setTranslationKey(TranslationInfo translationInfo)
			throws ApplicationException {
		Country country = translationInfo.getCountry();
		String key = null;
		if (country == null) {
			throw new BusinessException(
					new BusinessErrorCode(RLNTS_NOT_DEFINED));
		}
		Language language = translationInfo.getLanguage();
		if (language == null) {
			throw new BusinessException(
					new BusinessErrorCode(RLNTS_NOT_DEFINED));
		}
		key = language.getLanguageCode() + "_" + country.getCountryCode();
		translationInfo.setTranslationKey(key);
	}
}
